package com.bracket


import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.multi_select_list_layout.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun generateMixText(view: View) {
        val fakeSentence = fakeWord.editText!!.text.toString()
        val realSentence = heartWord.editText!!.text.toString()

        val fakeLen = fakeSentence.length
        val realLen = realSentence.length
        val stringBuilder = StringBuilder(fakeLen)
        for (k in 0 until fakeLen) {
            stringBuilder.append(fakeSentence[k])
            if (k < realLen) {
                stringBuilder.append('（')
                stringBuilder.append(realSentence[k])
                stringBuilder.append('）')
            }
        }
        val s = stringBuilder.toString()
        mixText.text = s

        val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.type = "text/plain"
        shareIntent.putExtra(Intent.EXTRA_TEXT, s)
        val sharedApps = packageManager.queryIntentActivities(shareIntent, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
        var installedApp = packageManager.getInstalledApplications(0)
        var appInfos = ArrayList<AppInfo>()
        installedApp.forEach { appInfo ->
            sharedApps.forEach {
                if (it.resolvePackageName == appInfo.packageName) {
                    appInfos.add(AppInfo(it.loadLabel(packageManager).toString(), it.loadIcon(packageManager), ComponentName(appInfo.packageName, it.activityInfo.targetActivity.toString())))
                }
            }
        }
        val alertDialog = AlertDialog.Builder(this)
                .setTitle(R.string.sharable_app)
                .setView(R.layout.multi_select_list_layout)
                .create()
        alertDialog.show()
        alertDialog.recyclerView.adapter = ShareAdapter(appInfos, object : ShareAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                val intent = Intent()
                intent.component = appInfos.get(position).packageName
                startActivity(shareIntent)
            }

        })

    }
}
